<template>
  <div class="category-container">
    <div class="action-bar">
      <el-button type="primary" icon="el-icon-plus" @click="handleAddCategory">添加节目类别</el-button>
      <el-input v-model="searchQuery" placeholder="搜索类别名称" prefix-icon="el-icon-search" clearable
        class="search-input" @clear="handleSearch" @keyup.enter.native="handleSearch">
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
    </div>

    <el-card shadow="hover" class="table-card">
      <el-table :data="categoryList" border stripe style="width: 100%" v-loading="loading" :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#606266' }">
        <el-table-column prop="programTypeId" label="ID" width="250" align="center"></el-table-column>
        <el-table-column prop="programTypeName" label="类别名称" width="250" align="center"></el-table-column>
        <el-table-column prop="description" label="描述" width="300" align="center"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="200" align="center"></el-table-column>
        <el-table-column prop="createUser" label="创建人" width="220" align="center"></el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="editCategory(scope.row)"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteCategory(scope.row)"></el-button>
          </template>
        </el-table-column>
        
      </el-table>

      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑类别对话框 -->
    <el-dialog :title="isEditMode ? '编辑节目类别' : '添加节目类别'" :visible.sync="dialogVisible" width="500px" center>
      <el-form :model="categoryForm" :rules="rules" ref="categoryForm" label-width="100px">
        <el-form-item label="类别名称" prop="name">
          <el-input v-model="categoryForm.programTypeName" placeholder="请输入类别名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="categoryForm.description" rows="3" placeholder="请输入描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCategory">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request';

export default {
  name: 'ProgramCategory',
  data() {
    return {
      categoryList: [],
      loading: false,
      searchQuery: '',
      dialogVisible: false,
      isEditMode: false,
      categoryForm: {
        programTypeId: '',
        programTypeName: '',
        description: '',
        createTime: '',
        createUser: '',
        token: localStorage.getItem('token')
      },
      rules: {
        programTypeName: [{ required: true, message: '请输入类别名称', trigger: 'blur' }]
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    };
  },
  created() {
    this.fetchCategoryList();
  },
  methods: {
    fetchCategoryList() {
      this.loading = true;
      service.get('/api/content/program/getProgramTypeList', {
        params: {
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          programTypeName: this.searchQuery
        }
      }).then(res => {
        if (res.code === 200) {
          this.categoryList = res.data.list;
          this.pagination.total = res.data.total;
        }
      }).catch(err => {
        this.$message.error('获取类别列表失败：' + err.message);
      }).finally(() => {
        this.loading = false;
      });
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchCategoryList();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.fetchCategoryList();
    },
    handleSearch() {
      this.pagination.currentPage = 1;
      this.fetchCategoryList();
    },
    handleAddCategory() {
      this.isEditMode = false;
      this.categoryForm = {
        programTypeId: '',
        programTypeName: '',
        description: '',
        createTime: '',
        createUser: '',
        token: localStorage.getItem('token')
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.categoryForm.clearValidate();
      });
    },
    editCategory(row) {
      this.isEditMode = true;
      this.categoryForm = JSON.parse(JSON.stringify(row));
      this.categoryForm.token = localStorage.getItem('token');
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.categoryForm.clearValidate();
      });
    },
    submitCategory() {
      this.$refs.categoryForm.validate(valid => {
        if (valid) {
          const request = this.isEditMode
            ? service.put(`/api/content/program/updateProgramType`, this.categoryForm)
            : service.post('/api/content/program/addProgramType', this.categoryForm);

          request.then(res => {
            if (res.code === 200) {
              this.$message.success(this.isEditMode ? '更新成功' : '添加成功');
              this.dialogVisible = false;
              this.fetchCategoryList();
            } else {
              this.$message.error(res.message || '操作失败');
            }
          }).catch(err => {
            this.$message.error('操作失败：' + err.message);
          });
        }
      });
    },
    deleteCategory(row) {
      this.$confirm('确认删除该节目类别？删除后将无法恢复！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        service.delete(`/api/content/program/deleteProgramType/${row.programTypeId}`).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.fetchCategoryList();
          } else {
            this.$message.error(res.message || '删除失败');
          }
        }).catch(err => {
          this.$message.error('删除失败：' + err.message);
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    }
  }
};
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.table-card {
  margin-bottom: 20px;
}


.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 